package com.iotimc.attendancesystem.welcome;

import android.content.Context;
import android.util.Log;

import com.iotimc.attendancesystem.App;
import com.iotimc.attendancesystem.R;
import com.iotimc.attendancesystem.attendance.SystemActivity;
import com.iotimc.attendancesystem.dao.GreenDaoManager;
import com.iotimc.attendancesystem.entity.PersonEntity;
import com.iotimc.attendancesystem.util.AssetsCopyer;
import com.pefis.natives.Ast2600JNI;
import com.pefis.natives.PfsBioInfo;

import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @author david
 * @date 2017/11/27
 */

public class WelcomePresenter implements WelcomeContract.Presenter {
    private static final String TAG = "WelcomePresenter";
    private String mStrDevId;
    private String mStrDevName;
    private int[] m_nContextID = new int[1];
    private File m_File = new File(PfsBioInfo.TEMPLATE_DB_PATH);

    private boolean mFlag = false;
    WelcomeContract.View view;
    Context context;

    public WelcomePresenter(WelcomeContract.View view, Context context) {
        this.view = view;
        this.context = context;
    }

    @Override
    public void initDevice() {
        Log.i(TAG, "initDevice: ");
        view.showLoading();
        Observable.timer(1, TimeUnit.SECONDS, Schedulers.io()).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                Log.i(TAG, "accept: " + PfsBioInfo.INIT_DATA_PATH);
                File file = new File(PfsBioInfo.INIT_DATA_PATH);
                //Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download"
                if (!file.exists()) {
                    file.mkdirs();
                } else if (!file.isDirectory() && file.canWrite()) {
                    file.delete();
                    file.mkdirs();
                }
                if (file.list().length == 0) {
                    AssetsCopyer.releaseAssets(context,
                            "GDFace", App.getAppContext().getFilesDir().getAbsolutePath());
                }
                init();
            }
        });
    }

    private void init() {

        int vnRet;
        int i = 0;
        byte[] vByteDeviceDescription = new byte[256];
        byte[] vDeviceIdentifier = new byte[256];

        vnRet = Ast2600JNI.getInstance().pisEnumerateDevice(i,
                vDeviceIdentifier, vByteDeviceDescription);
        if (vnRet == PfsBioInfo.PFSBIO_OK) {
            mStrDevId = Ast2600JNI.ByteArrayUtf8ToString(vDeviceIdentifier);
            mStrDevName = Ast2600JNI
                    .ByteArrayUtf8ToString(vByteDeviceDescription);

        } else {
            Log.i(TAG, "检测当前存在的设备错误 : vnRet = " + vnRet);
            mStrDevId = "";
            mStrDevName = "";
            mFlag = false;
            //-1
            view.showMessage(R.string.noDevice);
            return;
        }

        PfsBioInfo.getInstance().mEnrollID = -1;
        vnRet = Ast2600JNI.getInstance().pisCreateContext(m_nContextID);

        if (vnRet != PfsBioInfo.PFSBIO_OK) {
            Log.i(TAG, "USB口设备检测错误 : vnRet = " + vnRet);
            view.showMessage(R.string.initFail);
            //0
            return;
        }

        PfsBioInfo.getInstance().mContextID = m_nContextID[0];

        vnRet = Ast2600JNI.getInstance().pisOpenDevice(m_nContextID[0],
                mStrDevId.getBytes(), PfsBioInfo.INIT_DATA_PATH.getBytes());
        if (vnRet != PfsBioInfo.PFSBIO_OK) {
            Ast2600JNI.getInstance().pisDestroyContext(m_nContextID[0]);
            Log.i(TAG, "打开摄像头等设备错误 : vnRet = " + vnRet);
            mFlag = false;
            view.showMessage(R.string.initFail);
            //0
            return;
        }

        initDeviceDate();
        mFlag = true;
        //正常 1
        view.showMessage(R.string.initSuccuss);
    }

    @Override
    public void close() {
        if (mFlag) {
            Ast2600JNI.getInstance().pisCloseDevice(m_nContextID[0]);
            Ast2600JNI.getInstance().pisDestroyContext(m_nContextID[0]);
            mFlag = false;
        }
    }


    public void initDeviceDate() {
        Ast2600JNI.getInstance().pisFcClearTptArray(PfsBioInfo.getInstance().mContextID);

        try {

            // Get Face process parameters
            Ast2600JNI.getInstance().pisGetInfo(m_nContextID[0],
                    PfsBioInfo.PFSBIO_FACE_PARAM_KIND_IMG_W,
                    PfsBioInfo.getInstance().face_img_w);
            Ast2600JNI.getInstance().pisGetInfo(m_nContextID[0],
                    PfsBioInfo.PFSBIO_FACE_PARAM_KIND_IMG_H,
                    PfsBioInfo.getInstance().face_img_h);
            Ast2600JNI.getInstance().pisGetInfo(m_nContextID[0],
                    PfsBioInfo.PFSBIO_FACE_PARAM_KIND_TEMPLATE_SIZE,
                    PfsBioInfo.getInstance().enroll_template_size);
            Ast2600JNI.getInstance().pisGetInfo(m_nContextID[0],
                    PfsBioInfo.PFSBIO_FACE_PARAM_KIND_FEATURE_SIZE,
                    PfsBioInfo.getInstance().match_feature_size);
            Ast2600JNI.getInstance().pisGetInfo(m_nContextID[0],
                    PfsBioInfo.PFSBIO_FACE_PARAM_KIND_ENROLL_FACE_COUNT,
                    PfsBioInfo.getInstance().enroll_face_count);
            Log.i(TAG, "initDeviceDate: "+ PfsBioInfo.getInstance().enroll_template_size[0]);
            // LoadTemplateFiles();
            loadTempImageCode();
            // convertData();
        } catch (Exception e) {
            e.printStackTrace();
            Ast2600JNI.getInstance().pisCloseDevice(m_nContextID[0]);
            Ast2600JNI.getInstance().pisDestroyContext(m_nContextID[0]);
        }
    }


    private void loadTempImageCode() {
        List<PersonEntity> entities = GreenDaoManager.getInstance().getSession().getPersonEntityDao().loadAll();
        PfsBioInfo.getInstance().malloc_vars(context);
        if (entities.size() > 0) {
            int vnRet = 0;
            for (int i = 0; i < entities.size(); i++) {
                PersonEntity entity = entities.get(i);
                if (entity.getICodeId() != null && entity.getICodeId() != 0) {
                    vnRet = Ast2600JNI.getInstance().pisFcSetAtTptArray(
                            m_nContextID[0], entity.getICodeId(),
                            entity.getImageCode());
                    if (vnRet != PfsBioInfo.PFSBIO_OK) {
                        continue;
                    }
                }
            }
        }
        int[] i = new int[1];
        Ast2600JNI.getInstance().pisFcGetCountTptArray(m_nContextID[0],i);
        Log.i(TAG, "loadTempImageCode: "+i[0]);
    }


    /**
     * 检测或创建文件夹  设置模型数据
     */
    public void LoadTemplateFiles() {

        if (!m_File.isDirectory()) {
            if (!m_File.mkdir()) {
                return;
            }
        }

        File mPhotoDir = new File(PfsBioInfo.PHOTO_DB_PATH);
        if (mPhotoDir.isDirectory() == false) {
            if (mPhotoDir.mkdir() == false) {
                return;
            }

        }

        String[] vFileNameList = m_File.list();
        int vFileCounts = vFileNameList.length;
        int vnTemplateID;

        PfsBioInfo.getInstance().malloc_vars(context);

        int vReadRet;
        int vnRet = 0;
        while (vFileCounts != 0) {
            vReadRet = PfsBioInfo.getInstance().ReadByteFromFile(
                    PfsBioInfo.TEMPLATE_DB_PATH
                            + vFileNameList[vFileCounts - 1],
                    PfsBioInfo.getInstance().m_pTemplate,
                    PfsBioInfo.getInstance().enroll_template_size[0]);
            if (vReadRet == -1) {

                return;
            }
            vnTemplateID = 0;
            try {
                vnTemplateID = Integer.valueOf(vFileNameList[vFileCounts - 1]);
            } catch (Exception e) {
                e.printStackTrace();
            }

            vnRet = Ast2600JNI.getInstance().pisFcSetAtTptArray(
                    m_nContextID[0], (int) vnTemplateID,
                    PfsBioInfo.getInstance().m_pTemplate);
            if (vnRet != PfsBioInfo.PFSBIO_OK) {

                vFileCounts -= 1;
                continue;
            }
            vFileCounts -= 1;
        }

    }
}
